package acwing._1_1AlgorithmBasic._3SearchGraph;
/**
 * @Project : AlgorithmLearning
 * @Package : ACWing._1_1AlgorithmBasic._3SearchGraph
 * @File : Q0847.java
 * @Author : WangRuoyu
 * @Date : 2023/4/2 9:41
 */

import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class Q0847 {
    static int n;
    static int m;
    static int[] h;
    static int[] e;
    static int[] next;
    static int idx = 0;
    static boolean[] st;

    static void add(int a, int b) {
        e[idx] = b;
        next[idx] = h[a];
        h[a] = idx++;
    }

    static int bfs() {
        int res = -1;
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{1, 0});
        st[1] = true;
        while (!q.isEmpty()) {
            int[] point = q.poll();
            if (point[0] == n) {
                res = point[1];
                break;
            }
            for (int i = h[point[0]]; i != -1; i = next[i]) {
                int j = e[i];
                if (!st[j]) {
                    st[j] = true;
                    q.add(new int[]{j, point[1] + 1});
                }
            }
        }
        return res;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] words = br.readLine().split(" ");
        n = Integer.parseInt(words[0]);
        m = Integer.parseInt(words[1]);

        h = new int[n + 1];
        st = new boolean[n + 1];
        e = new int[2 * m + 10];
        next = new int[2 * m + 10];
        Arrays.fill(h, -1);

        for (int i = 0; i < m; ++i) {
            words = br.readLine().split(" ");
            int a = Integer.parseInt(words[0]);
            int b = Integer.parseInt(words[1]);
            add(a, b);
        }

        System.out.println(bfs());
    }
}